
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using SariturIntranetLibrary.Configuracoes;

namespace SariturIntranetLibrary.Servicos
{
    [Serializable()]
    public class SetorNameValueList : Csla.NameValueListBase<int, string>
    {

        #region Factory Methods
        private SetorNameValueList()
        { /* require use of factory method */ }

        public static SetorNameValueList GetSetorNameValueList()
        {
            return DataPortal.Fetch<SetorNameValueList>(new FilterCriteria());
        }

        public static SetorNameValueList GetSetorNameValueList(string emptyText)
        {
            return DataPortal.Fetch<SetorNameValueList>(new FilterCriteria(emptyText));
        }
        #endregion //Factory Methods


        #region Data Access
        class FilterCriteria
        {
            public string EmptyText = string.Empty;
            public FilterCriteria()
            { }
            public FilterCriteria(string emptyText)
            {
                this.EmptyText = emptyText;
            }
        }

        private void DataPortal_Fetch(FilterCriteria criteria)
        {
            RaiseListChangedEvents = false;

            using (SqlConnection cn = new SqlConnection(ConfigDatabase.SariturDBConnection))
            using (SqlCommand cm = cn.CreateCommand())
            {
                cn.Open();

                cm.CommandType = CommandType.StoredProcedure;
                cm.CommandText = "GetSetorNameValueList";

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    IsReadOnly = false;
                    if (criteria.EmptyText != string.Empty)
                        this.Add(new NameValuePair(0, criteria.EmptyText));
                    while (dr.Read())
                        this.Add(new NameValuePair(dr.GetInt32("Id"), dr.GetString("Setor")));
                    IsReadOnly = true;
                }
            }//using

            RaiseListChangedEvents = true;
        }
        #endregion //Data Access

    }
}
